<template>
	<view class="trade-publish-page">
		<view class="page-header">
			<text class="page-title">发布商品</text>
			<text class="page-subtitle">出售闲置物品</text>
		</view>

		<view class="form-container">
			<!-- 商品标题 -->
			<view class="form-item">
				<view class="item-label">
					<text class="label-text">商品标题</text>
					<text class="required-mark">*</text>
				</view>
				<up-input 
					v-model="formData.title" 
					placeholder="请输入商品标题（10-50字）" 
					:maxlength="50" 
					border="none"
				/>
			</view>

			<!-- 分类、价格、成色 -->
			<view class="form-row">
				<view class="form-item-half">
					<view class="item-label">
						<text class="label-text">商品分类</text>
						<text class="required-mark">*</text>
					</view>
					<view class="selector-input" @click="showCategoryPicker = true">
						<text class="selector-text" :class="{ placeholder: !formData.subCategory }">
							{{ formData.subCategory || '请选择' }}
						</text>
						<up-icon name="arrow-down" size="14" color="#999"></up-icon>
					</view>
				</view>

				<view class="form-item-half">
					<view class="item-label">
						<text class="label-text">物品成色</text>
						<text class="required-mark">*</text>
					</view>
					<view class="selector-input" @click="showConditionPicker = true">
						<text class="selector-text" :class="{ placeholder: !formData.condition }">
							{{ formData.condition || '请选择' }}
						</text>
						<up-icon name="arrow-down" size="14" color="#999"></up-icon>
					</view>
				</view>
			</view>

			<!-- 商品价格 -->
			<view class="form-item">
				<view class="item-label">
					<text class="label-text">商品价格（元）</text>
					<text class="required-mark">*</text>
				</view>
				<up-input 
					v-model="formData.price" 
					type="number" 
					placeholder="请输入价格"
					border="none"
				>
					<template #prefix>
						<text style="color: #ED8936; font-weight: 600; margin-right: 8rpx;">¥</text>
					</template>
				</up-input>
			</view>

			<!-- 商品描述 -->
			<view class="form-item">
				<view class="item-label">
					<text class="label-text">商品描述</text>
					<text class="required-mark">*</text>
				</view>
				<up-textarea 
					v-model="formData.content" 
					placeholder="请详细描述商品情况（至少10字）" 
					:maxlength="500"
					count
					:autoHeight="true"
					height="200rpx"
				/>
			</view>

			<!-- 商品图片 -->
			<view class="form-item">
				<view class="item-label">
					<text class="label-text">商品图片</text>
					<text class="label-hint">（最多9张）</text>
				</view>
				<view class="image-list">
					<view class="image-item" v-for="(image, index) in formData.images" :key="index">
						<image :src="image" mode="aspectFill" class="image" />
						<view class="delete-btn" @click="handleDeleteImage(index)">
							<up-icon name="close-circle-fill" color="#fff" size="18"></up-icon>
						</view>
					</view>
					
					<view class="upload-btn" v-if="formData.images.length < 9" @click="handleChooseImage">
						<up-icon name="camera" size="32" color="#999"></up-icon>
					</view>
				</view>
			</view>

			<!-- 联系方式和交易方式 -->
			<view class="form-item">
				<view class="item-label">
					<text class="label-text">联系方式</text>
					<text class="required-mark">*</text>
				</view>
				<up-input 
					v-model="formData.contactInfo" 
					placeholder="请输入微信号、QQ号或手机号" 
					:maxlength="50"
					border="none"
				/>
			</view>

			<view class="form-item">
				<view class="item-label">
					<text class="label-text">交易方式</text>
				</view>
				<view class="selector-input" @click="showMethodPicker = true">
					<text class="selector-text" :class="{ placeholder: !tradeMethodsText }">
						{{ tradeMethodsText || '请选择交易方式' }}
					</text>
					<up-icon name="arrow-down" size="14" color="#999"></up-icon>
				</view>
			</view>

			<!-- 提交按钮 -->
			<view class="submit-container">
				<up-button 
					type="primary" 
					size="large" 
					@click="handleSubmit" 
					:loading="submitting"
					:customStyle="{
						background: 'linear-gradient(135deg, #ED8936 0%, #dd7c29 100%)',
						border: 'none'
					}"
				>
					{{ submitting ? '发布中...' : '立即发布' }}
				</up-button>
			</view>
		</view>

		<!-- 分类选择器 -->
		<up-picker 
			v-model:show="showCategoryPicker" 
			:columns="categoryColumns"
			@confirm="onCategoryConfirm"
			@cancel="showCategoryPicker = false"
		></up-picker>

		<!-- 成色选择器 -->
		<up-picker 
			v-model:show="showConditionPicker" 
			:columns="conditionColumns"
			@confirm="onConditionConfirm"
			@cancel="showConditionPicker = false"
		></up-picker>

		<!-- 交易方式选择器 -->
		<up-picker 
			v-model:show="showMethodPicker" 
			:columns="methodColumns"
			@confirm="onMethodConfirm"
			@cancel="showMethodPicker = false"
		></up-picker>
	</view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { mockAddPost } from '../../server/mock.js';

// 表单引用
const formRef = ref(null);
const submitting = ref(false);

// 选择器显示状态
const showCategoryPicker = ref(false);
const showConditionPicker = ref(false);
const showMethodPicker = ref(false);

// 表单数据
const formData = reactive({
	title: '',
	subCategory: '电子产品',
	price: '',
	condition: '9成新',
	content: '',
	images: [],
	contactInfo: '',
	tradeMethods: ['线下见面']
});

// 分类选项
const categoryColumns = [
	['电子产品', '生活用品', '图书资料', '运动器材', '服饰鞋包', '其他']
];

// 成色选项
const conditionColumns = [
	['全新', '99新', '9成新', '8成新', '7成新']
];

// 交易方式选项
const methodColumns = [
	['线下见面', '同城配送', '快递邮寄']
];

// 交易方式显示文本
const tradeMethodsText = computed(() => {
	return formData.tradeMethods.join('、') || '请选择';
});

// 分类确认
const onCategoryConfirm = ({ value }) => {
	formData.subCategory = value[0];
	showCategoryPicker.value = false;
};

// 成色确认
const onConditionConfirm = ({ value }) => {
	formData.condition = value[0];
	showConditionPicker.value = false;
};

// 交易方式确认
const onMethodConfirm = ({ value }) => {
	formData.tradeMethods = [value[0]];
	showMethodPicker.value = false;
};

// 表单验证规则
const rules = {
	title: [
		{ required: true, message: '请输入商品标题', trigger: 'blur' },
		{ min: 10, max: 50, message: '标题长度在 10 到 50 个字符', trigger: 'blur' }
	],
	subCategory: [
		{ required: true, message: '请选择商品分类', trigger: 'change' }
	],
	price: [
		{ required: true, message: '请输入价格', trigger: 'blur' },
		{
			validator: (rule, value, callback) => {
				if (value <= 0) {
					callback(new Error('价格必须大于0'));
				} else {
					callback();
				}
			},
			trigger: 'blur'
		}
	],
	condition: [
		{ required: true, message: '请选择物品成色', trigger: 'change' }
	],
	content: [
		{ required: true, message: '请输入商品描述', trigger: 'blur' },
		{ min: 10, max: 500, message: '描述长度在 10 到 500 个字符', trigger: 'blur' }
	],
	contactInfo: [
		{ required: true, message: '请输入联系方式', trigger: 'blur' }
	]
};

/**
 * 选择图片
 */
const handleChooseImage = () => {
	uni.chooseImage({
		count: 9 - formData.images.length,
		sizeType: ['compressed'],
		sourceType: ['album', 'camera'],
		success: (res) => {
			formData.images.push(...res.tempFilePaths);
		}
	});
};

/**
 * 删除图片
 */
const handleDeleteImage = (index) => {
	formData.images.splice(index, 1);
};

/**
 * 提交表单
 */
const handleSubmit = async () => {
	// 检查登录状态
	const token = uni.getStorageSync('token');
	if (!token) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		});
		setTimeout(() => {
			uni.navigateTo({
				url: '/pages/login/login'
			});
		}, 1000);
		return;
	}

	// 验证图片
	if (formData.images.length === 0) {
		uni.showToast({
			title: '请至少上传一张商品图片',
			icon: 'none'
		});
		return;
	}

	// 表单验证
	formRef.value.validate().then(async (valid) => {
		if (valid) {
			submitting.value = true;

			try {
				// 构造帖子数据
				const postData = {
					title: formData.title,
					content: formData.content,
					image: formData.images,
					plateId: 3, // 交易区板块ID
					subCategory: formData.subCategory,
					tradePrice: parseFloat(formData.price),
					tradeStatus: 'available',
					tradeCondition: formData.condition,
					contactInfo: formData.contactInfo,
					tradeMethods: formData.tradeMethods.join('、')
				};

				const res = await mockAddPost(postData);

				if (res.code === 200) {
					uni.showToast({
						title: '发布成功',
						icon: 'success'
					});

					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} else {
					uni.showToast({
						title: res.message || '发布失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('发布商品失败:', error);
				uni.showToast({
					title: '发布失败，请重试',
					icon: 'none'
				});
			} finally {
				submitting.value = false;
			}
		}
	}).catch(() => {
		uni.showToast({
			title: '请完善表单信息',
			icon: 'none'
		});
	});
};
</script>

<style lang="scss" scoped>
@import '../../styles/variables.scss';
@import '../../styles/mixins.scss';

.trade-publish-page {
	min-height: 100vh;
	background: $bg-page;

	.page-header {
		background: linear-gradient(135deg, $plate-trade 0%, darken($plate-trade, 10%) 100%);
		padding: $spacing-xxl;
		padding-top: 120rpx;
		text-align: center;
		color: #fff;

		.page-title {
			font-size: $font-xxl;
			font-weight: $font-bold;
			margin-bottom: $spacing-xs;
		}

		.page-subtitle {
			font-size: $font-sm;
			opacity: 0.9;
		}
	}

	.form-container {
		padding: $spacing-lg;

		.form-item {
			@include card;
			padding: $spacing-lg;
			margin-bottom: $spacing-base;

			.item-label {
				@include flex-between;
				margin-bottom: $spacing-base;

				.label-text {
					font-size: $font-base;
					color: $text-primary;
					font-weight: $font-semibold;
				}

				.required-mark {
					color: $error-color;
					margin-left: $spacing-xs;
				}

				.label-hint {
					font-size: $font-sm;
					color: $text-tertiary;
				}
			}

			.selector-input {
				@include flex-between;
				padding: $spacing-base;
				background: $bg-page;
				border-radius: $radius-base;
				border: 1px solid $border-light;

				.selector-text {
					font-size: $font-base;
					color: $text-primary;
					
					&.placeholder {
						color: $text-tertiary;
					}
				}
			}
		}

		.form-row {
			display: flex;
			gap: $spacing-base;
			margin-bottom: $spacing-base;

			.form-item-half {
				flex: 1;
				@include card;
				padding: $spacing-lg;

				.item-label {
					@include flex-between;
					margin-bottom: $spacing-base;

					.label-text {
						font-size: $font-base;
						color: $text-primary;
						font-weight: $font-semibold;
					}

					.required-mark {
						color: $error-color;
						margin-left: $spacing-xs;
					}
				}

				.selector-input {
					@include flex-between;
					padding: $spacing-base;
					background: $bg-page;
					border-radius: $radius-base;
					border: 1px solid $border-light;

					.selector-text {
						font-size: $font-base;
						color: $text-primary;
						
						&.placeholder {
							color: $text-tertiary;
						}
					}
				}
			}
		}

		.image-list {
			display: flex;
			flex-wrap: wrap;
			gap: $spacing-base;

			.image-item {
				position: relative;
				width: 200rpx;
				height: 200rpx;
				border-radius: $radius-md;
				overflow: hidden;

				.image {
					width: 100%;
					height: 100%;
				}

				.delete-btn {
					position: absolute;
					top: $spacing-xs;
					right: $spacing-xs;
					width: 40rpx;
					height: 40rpx;
					@include flex-center;
					background: rgba(0, 0, 0, 0.6);
					border-radius: $radius-round;
				}
			}

			.upload-btn {
				width: 200rpx;
				height: 200rpx;
				@include flex-center;
				background: $bg-page;
				border: 2rpx dashed $border-base;
				border-radius: $radius-md;

				&:active {
					background: $bg-hover;
					border-color: $plate-trade;
				}
			}
		}

		.submit-container {
			margin-top: $spacing-xl;
		}
	}
}
</style>

